package com.climb.spingcloud.controller;

import com.climb.spingcloud.base.R;
import com.climb.spingcloud.conver.OrderConvert;
import com.climb.spingcloud.dto.ProductDto;
import com.climb.spingcloud.entity.Order;
import com.climb.spingcloud.feign.RemoteProductService;
import com.climb.spingcloud.service.OrderService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Administrator-NANA
 * @date 2021-08-02 14:40:42
 * @description
 */
@Slf4j
@RestController
@RequestMapping("/orders")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private RemoteProductService productService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    //准备买一件商品
    @PostMapping("")
    public R order(Long productId) throws JsonProcessingException {
        log.info(">>客户下单，使用{}号调用商品微服务查询商品信息", productId);
        //通过feign调用微服务
        R<ProductDto> result=productService.getById(productId);
        ProductDto productDto=result.getData();
        log.info(">>查询{}号商品信息,查询结果:{}", productId, new ObjectMapper().writeValueAsString(productDto));
        //下单
        Order order = new Order();
        order.setUserId(1L);
        order.setUserName("测试用户");
        order.setProductId(productDto.getId());
        order.setProductName(productDto.getName());
        order.setProductPrice(productDto.getPrice());
        order.setNumber(1);// 默认1件商品
        orderService.save(order);
        log.info(">>创建订单成功,订单信息为:{}" + new ObjectMapper().writeValueAsString(order));

        //下的那成功后发送消息给mq.第一个参数是topic或topic:tag,第二个参数是消息体
        rocketMQTemplate.convertAndSend("myorder-topic:tag1", OrderConvert.INSTANCE.entity2dto(order));
        return R.success();
    }

}
